﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using vxi.chat.library;
using System.Resources;
using System.Reflection;
using System.Drawing.Text;
using Telerik.WinControls.UI.Docking;
using Telerik.WinControls.UI;
using ChatContext;
using ChatEntities;
using vxi.com.log;
using System.IO;
using System.Collections.ObjectModel;
using vxi.com.server;
using System.Linq;
using System.Net;
using vxi.com.appsetting;

namespace vxi.chat.server
{
    public partial class RadMainForm : Telerik.WinControls.UI.RadRibbonForm
    {
        #region 自定义变量

        private Setting _setting;
        private VxiServer _server;
        private ObservableCollection<ChatLog> _log;
        private ObservableCollection<ChatLog> _event;
        private ObservableCollection<ChatLog> _sql;
        private bool isfirstshowlog;
        private bool isfirstshowevent;
        private bool isfirstshowsql;

        #endregion

        #region 初始化

        /// <summary>
        /// 构造函数
        /// </summary>
        public RadMainForm()
        {
            Initialize();
        }

        private void Initialize()
        {
            InitializeComponent();
            _setting = new Setting();
            _setting.LoadSetting(Application.StartupPath);
            this.LoadFromSetting();
            isfirstshowlog = isfirstshowevent = isfirstshowsql = true;
            _log = new ObservableCollection<ChatLog>();
            _event = new ObservableCollection<ChatLog>();
            _sql = new ObservableCollection<ChatLog>();
            _log.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_log_CollectionChanged);
            _event.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_event_CollectionChanged);
            _sql.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_sql_CollectionChanged);
            ThemeResolutionService.ApplicationThemeName = "Office2010Blue";
            Font font = new Font("Arial", float.Parse("8.75"));
            RichTextBoxLanguageOptions options = RichTextBoxLanguageOptions.UIFonts;
            this.richTextBox1.Font = this.richTextBox2.Font = this.richTextBox3.Font = font;
            this.richTextBox1.LanguageOption = this.richTextBox2.LanguageOption = this.richTextBox3.LanguageOption = options;
            this.radRibbonBar1.RibbonBarElement.ApplicationButtonElement.Text = "Option";
            this.radRibbonBar1.RibbonBarElement.ApplicationButtonElement.ForeColor = Color.White;
            this.radRibbonBar1.RibbonBarElement.ApplicationButtonElement.DisplayStyle = DisplayStyle.Text;
            this.notifyIcon1.Icon = global::VisionChatServer.Properties.Resources.remove_server;
            radButton_StopSerivce.Enabled = false;
        }

        void _sql_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add && radLockBoardBtn.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                if (isfirstshowsql)
                {
                    richTextBox3.Clear();
                    foreach (ChatLog l in _sql)
                    {
                        if (this.richTextBox3.Lines.Length > 0)
                            this.richTextBox3.AppendText(Environment.NewLine);
                        this.richTextBox3.SelectionColor = Color.Black;
                        this.richTextBox3.AppendText(l.log);
                    }
                    isfirstshowsql = false;
                }
                else
                {
                    if (this.richTextBox3.Lines.Length > 0)
                        this.richTextBox3.AppendText(Environment.NewLine);
                    if (this.richTextBox1.Lines.Length > 1024)
                    {
                        int start = richTextBox3.GetFirstCharIndexFromLine(0);//第一行第一个字符的索引
                        int end = richTextBox3.GetFirstCharIndexFromLine(1);//第n行第一个字符的索引
                        richTextBox3.Select(start, end);//选中第一行
                        richTextBox3.SelectedText = "";//设置第一行的内容为空
                    }
                    this.richTextBox3.SelectionColor = Color.Black;
                    this.richTextBox3.AppendText((e.NewItems[0] as ChatLog).log);
                }
            }
        }

        void _event_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add && radLockBoardBtn.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                if (isfirstshowevent)
                {
                    richTextBox2.Clear();
                    foreach (ChatLog l in _event)
                    {
                        if (this.richTextBox2.Lines.Length > 0)
                            this.richTextBox2.AppendText(Environment.NewLine);
                        this.richTextBox2.SelectionColor = Color.Black;
                        this.richTextBox2.AppendText(l.log);
                    }
                    isfirstshowevent = false;
                }
                else
                {
                    if (this.richTextBox2.Lines.Length > 0)
                        this.richTextBox2.AppendText(Environment.NewLine);
                    if (this.richTextBox2.Lines.Length > 1024)
                    {
                        int start = richTextBox2.GetFirstCharIndexFromLine(0);//第一行第一个字符的索引
                        int end = richTextBox2.GetFirstCharIndexFromLine(1);//第n行第一个字符的索引
                        richTextBox2.Select(start, end);//选中第一行
                        richTextBox2.SelectedText = "";//设置第一行的内容为空
                    }
                    this.richTextBox2.SelectionColor = Color.Black;
                    this.richTextBox2.AppendText((e.NewItems[0] as ChatLog).log);
                }
            }
        }

        void _log_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add && radLockBoardBtn.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                if (isfirstshowlog)
                {
                    richTextBox1.Clear();
                    foreach (ChatLog l in _log)
                    {
                        if (this.richTextBox1.Lines.Length > 0)
                            this.richTextBox1.AppendText(Environment.NewLine);
                        if (l.type == LogType.Exception)
                            this.richTextBox1.SelectionColor = Color.Red;
                        else
                            this.richTextBox1.SelectionColor = Color.Black;
                        this.richTextBox1.AppendText(l.log);
                    }
                    isfirstshowlog = false;
                }
                else
                {
                    if (this.richTextBox1.Lines.Length > 0)
                        this.richTextBox1.AppendText(Environment.NewLine);
                    if (this.richTextBox1.Lines.Length > 1024)
                    {
                        int start = richTextBox1.GetFirstCharIndexFromLine(0);//第一行第一个字符的索引
                        int end = richTextBox1.GetFirstCharIndexFromLine(1);//第n行第一个字符的索引
                        richTextBox1.Select(start, end);//选中第一行
                        richTextBox1.SelectedText = "";//设置第一行的内容为空
                    }
                    if ((e.NewItems[0] as ChatLog).type == LogType.Exception)
                        this.richTextBox1.SelectionColor = Color.Red;
                    else
                        this.richTextBox1.SelectionColor = Color.Black;
                    this.richTextBox1.AppendText((e.NewItems[0] as ChatLog).log);
                }
            }


        }

        #endregion

        #region 委托的实现

        /// <summary>
        /// 显示跟踪消息
        /// </summary>
        /// <param name="msg"></param>
        public void server_OnWriteLog(string _msg, LogType type)
        {
            switch (type)
            {
                case LogType.General:
                    {
                        if (_log.Count > 1024)
                            _log.RemoveAt(0);
                        _log.Add(new ChatLog(_msg,type));
                        break;
                    }
                case LogType.Event:
                    {
                        if (_event.Count > 1024)
                            _event.RemoveAt(0);
                        _event.Add(new ChatLog(_msg, type));
                        break;
                    }
                case LogType.Exception:
                    {
                        if (_log.Count > 1024)
                            _log.RemoveAt(0);
                        _log.Add(new ChatLog(_msg, type));
                        break;
                    }
                case LogType.Sql:
                    {
                        if (_sql.Count > 1024)
                            _sql.RemoveAt(0);
                        _sql.Add(new ChatLog(_msg, type));
                        break;
                    }
                default: break;
            }
        }

        public void server_OnQuantity_User(int num1,int num2)
        {
            linkCustomer.Text = string.Format("Customer:{0}", num2);
            linkAgent.Text = string.Format("Agent:{0}", num1);
        }

        public void server_OnQuantity_Session(int num1,int num2)
        {
            linkSession.Text = string.Format("Session:{0}", num1);

        }

        #endregion

        #region 按钮事件

        private void radButtonElement1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", Path.Combine(Application.StartupPath, "VisionChatLog"));
        }

        private void radButton_StartSerivce_Click(object sender, EventArgs e)
        {
            SaveFromSetting();
            _server = new VxiServer();
            _server.OnWriteLog += new WriteLogHandle(server_OnWriteLog);
            _server.OnQuantitySession += new QuantityHandle(server_OnQuantity_Session);
            _server.OnQuantityUser += new QuantityHandle(server_OnQuantity_User);
            try
            {
                if (_server.Start())
                {
                    radButton_StartSerivce.Enabled = false;
                    radButton_StopSerivce.Enabled = true;

                    backstageViewPage2.Enabled = false;

                    this.notifyIcon1.Icon = global::VisionChatServer.Properties.Resources.enable_server;
                }
            }
            catch (Exception ex)
            {
                _server.OnWriteLog(ex.Message, LogType.Exception);
            }
        }

        private void radButton_StopSerivce_Click(object sender, EventArgs e)
        {
            if (_server != null)
            {
                if (RadMessageBox.Show("Make sure to stop operating it? ", "Question", MessageBoxButtons.YesNo, RadMessageIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    _server.Stop();
                    radButton_StartSerivce.Enabled = true;
                    radButton_StopSerivce.Enabled = false;

                    backstageViewPage2.Enabled = true;

                    this.notifyIcon1.Icon = global::VisionChatServer.Properties.Resources.remove_server;
                }
            }
        }

        private void radButton_About_Click(object sender, EventArgs e)
        {
            RadAboutBox about = new RadAboutBox();
            about.ShowDialog();
        }

        private void radButton1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
        }

        private void radMenuItem1_Click(object sender, EventArgs e)
        {
            radDock1.DockWindow(toolWindow2, DockPosition.Bottom);
            radDock1.AutoHideWindow(toolWindow2);
        }

        private void radMenuItem2_Click(object sender, EventArgs e)
        {
            radDock1.FloatWindow(toolWindow2, Rectangle.Empty);
        }

        private void radMenuItem3_Click(object sender, EventArgs e)
        {
            radDock1.DockWindow(toolWindow1, DockPosition.Bottom);
            radDock1.AutoHideWindow(toolWindow1);
        }

        private void radMenuItem4_Click(object sender, EventArgs e)
        {
            radDock1.FloatWindow(toolWindow1, Rectangle.Empty);
        }

        private void radMenuItem5_Click(object sender, EventArgs e)
        {
            radDock1.DockWindow(documentWindow1, DockPosition.Fill);
        }

        private void radMenuItem6_Click(object sender, EventArgs e)
        {
            radDock1.FloatWindow(documentWindow1, Rectangle.Empty);
        }

        private void radBtnAddSyncServ_Click(object sender, EventArgs e)
        {
            RadAddSyncServ add = new RadAddSyncServ();
            add.ShowInTaskbar = false;
            if (add.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                ListViewDataItem item = new ListViewDataItem(add.radTextBoxNetSynIP.Text, new string[] { add.radTextBoxNetSynIP.Text, add.radTextBoxNetSynProt.Text });
                item.Tag = add.radTextBoxNetSynProt.Text;
                radListView1.Items.Add(item);
                
            }
        }

        private void radBtnDelSyncServ_Click(object sender, EventArgs e)
        {
            ListViewDataItem item = radListView1.SelectedItem as ListViewDataItem;
            if (item != null)
            {
                radListView1.Items.Remove(item);
            }
        }

        private void radButton_Save_Click(object sender, EventArgs e)
        {
            SaveFromSetting();
            RadMessageBox.Show("Save sucess.", "Infomation", MessageBoxButtons.OK, RadMessageIcon.Info);
        }

        #endregion




        #region 控件事件

        private void radLockBoardBtn_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args)
        {
            if (radLockBoardBtn.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                radLockBoardBtn.ImageIndex = 30;
                radLockBoardBtn.ToolTipText = "Show Log";
            }
            else
            {
                isfirstshowlog = isfirstshowevent = isfirstshowsql = true;
                radLockBoardBtn.ImageIndex = 29;
                radLockBoardBtn.ToolTipText = "Hide Log";
            }
        }

        private void RadMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_server != null && _server.isRun)
                _server.Stop();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = true;
                this.Show();
                this.Activate();
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void RadMainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
                this.Hide();
            }
        }

        private void radRibbonBarBackstageView1_BackstageViewOpening(object sender, CancelEventArgs e)
        {
            LoadFromSetting();
        }



        #endregion


        private void LoadFromSetting()
        {
            radTextBoxPort.Text = _setting.GlobalSetting.SERVER_PORT.ToString();
            radTextBoxSynPort.Text = _setting.GlobalSetting.SERVER_SYNC_PROT.ToString();
            radListView1.Items.Clear();
            foreach (IPEndPoint ip in _setting.GlobalSetting.SYNC_SERVER)
            {
                ListViewDataItem item = new ListViewDataItem(ip.Address.ToString(), new string[] { ip.Address.ToString(), ip.Port.ToString() });
                item.Tag = ip.Port.ToString();
                radListView1.Items.Add(item);
            }
        }

        private void SaveFromSetting()
        {
            _setting.GlobalSetting.SERVER_PORT = int.Parse(radTextBoxPort.Text);
            _setting.GlobalSetting.SERVER_SYNC_PROT = int.Parse(radTextBoxSynPort.Text);
            _setting.GlobalSetting.SYNC_SERVER.Clear();
            foreach (ListViewDataItem item in radListView1.Items)
            {
                _setting.GlobalSetting.SYNC_SERVER.Add(new IPEndPoint(IPAddress.Parse(item.Text), int.Parse(item.Tag.ToString())));
            }
            _setting.SaveSetting(Application.StartupPath);

            VxiDefine.SERVER_PORT = _setting.GlobalSetting.SERVER_PORT;
            VxiDefine.SERVER_SYNC_PROT = _setting.GlobalSetting.SERVER_SYNC_PROT;
            VxiDefine.SERVER_SYNC_NET = _setting.GlobalSetting.SYNC_SERVER;
        }

        #region 计时器
        /// <summary>
        /// 扫描在线客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void scanTimer_Tick(object sender, EventArgs e)
        {
            if (_server != null && _server.isRun)
            {
                _server.Scan();
            }
        }

        #endregion

        #region ToolWindow

        ToolWindow CreatePanel(string caption, DockPosition dockPosition, Size size, Color backColor)
        {
            ToolWindow panel = new ToolWindow();
            panel.CloseAction = DockWindowCloseAction.Close;
            panel.Text = caption;
            panel.BackColor = backColor;
            panel.Size = size;
            this.radDock1.DockWindow(panel, dockPosition);
            return panel;
        }

        private void linkAgent_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_server != null && _server.isRun)
            {
                ToolWindow panel = CreatePanel("Agent Window", DockPosition.Bottom, new Size(0, 0), Color.White);
                RadButton button = new RadButton() { Text = "Refresh", Dock = DockStyle.Top };
                button.ImageList = imageList1;
                button.TextAlignment = ContentAlignment.MiddleLeft;
                button.ImageAlignment = ContentAlignment.MiddleRight;
                button.TextImageRelation = TextImageRelation.ImageBeforeText;
                button.ImageIndex = 32;
                RadListView view = new RadListView() { Dock = DockStyle.Fill };
                view.FullRowSelect = true;
                ListViewDetailColumn c1 = new ListViewDetailColumn("UserName") { Width = 100,HeaderText = "UserName" };
                ListViewDetailColumn c2 = new ListViewDetailColumn("IPAddress") { Width = 150,HeaderText = "IPAddress" };
                ListViewDetailColumn c3 = new ListViewDetailColumn("LoginServer") { Width = 110, HeaderText = "LoginServer" };
                view.Columns.AddRange(new ListViewDetailColumn[] { c1, c2, c3 });
                view.ViewType = ListViewType.DetailsView;
                button.Click += (s, ex) =>
                    {
                        view.Items.Clear();
                        foreach (VxiAgent agent in _server.UserCollections.OfType<VxiAgent>().Cast<VxiAgent>())
                        {
                            ListViewDataItem item = new ListViewDataItem(agent.UserName, new string[] { agent.UserName, string.Format("{0}:{1}", agent.RemotePoint.Address.ToString(), agent.RemotePoint.Port.ToString()), agent.ServerName });
                            view.Items.Add(item);
                        }
                    };

                foreach (VxiAgent agent in _server.UserCollections.OfType<VxiAgent>().Cast<VxiAgent>())
                {
                    ListViewDataItem item = new ListViewDataItem(agent.UserName, new string[] { agent.UserName, string.Format("{0}:{1}", agent.RemotePoint.Address.ToString(), agent.RemotePoint.Port.ToString()), agent.ServerName });
                    view.Items.Add(item);
                }
                panel.Controls.Add(view);
                panel.Controls.Add(button);
                radDock1.FloatWindow(panel, Rectangle.FromLTRB((Screen.PrimaryScreen.WorkingArea.Width - 400) / 2, (Screen.PrimaryScreen.WorkingArea.Height - 400) / 2, (Screen.PrimaryScreen.WorkingArea.Width + 400) / 2, (Screen.PrimaryScreen.WorkingArea.Height + 400) / 2));
            }
        }

        private void linkCustomer_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_server != null && _server.isRun)
            {
                ToolWindow panel = CreatePanel("Customer Window", DockPosition.Bottom, new Size(0, 0), Color.White);
                RadButton button = new RadButton() { Text = "Refresh", Dock = DockStyle.Top };
                button.ImageList = imageList1;
                button.TextAlignment = ContentAlignment.MiddleLeft;
                button.ImageAlignment = ContentAlignment.MiddleRight;
                button.TextImageRelation = TextImageRelation.ImageBeforeText;
                button.ImageIndex = 32;
                RadListView view = new RadListView() { Dock = DockStyle.Fill };
                view.FullRowSelect = true;
                ListViewDetailColumn c1 = new ListViewDetailColumn("UserName") { Width = 100, HeaderText = "UserName" };
                ListViewDetailColumn c2 = new ListViewDetailColumn("IPAddress") { Width = 150, HeaderText = "IPAddress" };
                ListViewDetailColumn c3 = new ListViewDetailColumn("LoginServer") { Width = 110, HeaderText = "LoginServer" };
                view.Columns.AddRange(new ListViewDetailColumn[] { c1, c2, c3 });
                view.ViewType = ListViewType.DetailsView;
                button.Click += (s, ex) =>
                {
                    view.Items.Clear();
                    foreach (VxiCustomer agent in _server.UserCollections.OfType<VxiCustomer>().Cast<VxiCustomer>())
                    {
                        ListViewDataItem item = new ListViewDataItem(agent.UserName, new string[] { agent.UserName, string.Format("{0}:{1}", agent.RemotePoint.Address.ToString(), agent.RemotePoint.Port.ToString()), agent.ServerName });
                        view.Items.Add(item);
                    }
                };

                foreach (VxiCustomer agent in _server.UserCollections.OfType<VxiCustomer>().Cast<VxiCustomer>())
                {
                    ListViewDataItem item = new ListViewDataItem(agent.UserName, new string[] { agent.UserName, string.Format("{0}:{1}", agent.RemotePoint.Address.ToString(), agent.RemotePoint.Port.ToString()), agent.ServerName });
                    view.Items.Add(item);
                }
                panel.Controls.Add(view);
                panel.Controls.Add(button);
                radDock1.FloatWindow(panel,Rectangle.FromLTRB((Screen.PrimaryScreen.WorkingArea.Width - 400)/2,(Screen.PrimaryScreen.WorkingArea.Height - 400)/2,(Screen.PrimaryScreen.WorkingArea.Width +400)/2,(Screen.PrimaryScreen.WorkingArea.Height +400)/2 ));
            }
        }

        private void linkSession_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_server != null && _server.isRun)
            {
                ToolWindow panel = CreatePanel("Session Window", DockPosition.Bottom, new Size(0, 0), Color.White);
                RadButton button = new RadButton() { Text = "Refresh", Dock = DockStyle.Top };
                button.ImageList = imageList1;
                button.TextAlignment = ContentAlignment.MiddleLeft;
                button.ImageAlignment = ContentAlignment.MiddleRight;
                button.TextImageRelation = TextImageRelation.ImageBeforeText;
                button.ImageIndex = 32;
                RadGridView radGridView1 = new RadGridView() { Dock = DockStyle.Fill, AllowAddNewRow = false, AllowDeleteRow = false, EnableGrouping = false,AllowEditRow = false };
                using (radGridView1.DeferRefresh())
                {
                    radGridView1.MasterTemplate.Reset();
                    SetupMasterForUnbound(radGridView1);
                    SetupChildForUnbound(radGridView1);
                    GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate, radGridView1.Templates[0]);
                    relation.RelationName = "SessionOrders";
                    relation.ParentColumnNames.Add("SessionID");
                    relation.ChildColumnNames.Add("SessionID"); 
                    radGridView1.Relations.Add(relation);

                }
                button.Click += (s, ex) =>
                {
                    LoadDataForUnbound(radGridView1);
                    
                };
                LoadDataForUnbound(radGridView1);
                SetupFiltering(radGridView1.MasterTemplate, true);
                panel.Controls.Add(radGridView1);
                panel.Controls.Add(button);

                radDock1.FloatWindow(panel, Rectangle.FromLTRB((Screen.PrimaryScreen.WorkingArea.Width - 800) / 2, (Screen.PrimaryScreen.WorkingArea.Height - 600) / 2, (Screen.PrimaryScreen.WorkingArea.Width + 400) / 2, (Screen.PrimaryScreen.WorkingArea.Height + 400) / 2));
            }
        }

        private void SetupMasterForUnbound(RadGridView radGridView1) 
        {
            radGridView1.TableElement.RowHeight = 20;
            GridViewTextBoxColumn textColumn1 = new GridViewTextBoxColumn("SessionID"); 
            textColumn1.Width = 80;
            textColumn1.HeaderText = "SessionID"; 
            radGridView1.MasterTemplate.Columns.Add(textColumn1);
            GridViewDateTimeColumn dateTimeColumn = new GridViewDateTimeColumn("SessionBeginTime");
            dateTimeColumn.Width = 140; 
            dateTimeColumn.HeaderText = "StartTime"; 
            radGridView1.MasterTemplate.Columns.Add(dateTimeColumn);
            GridViewTextBoxColumn textColumn2 = new GridViewTextBoxColumn("SeesionMember");
            textColumn2.Width = 100;
            textColumn2.HeaderText = "Number of Client";
            radGridView1.MasterTemplate.Columns.Add(textColumn2);
            radGridView1.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            radGridView1.MasterTemplate.ShowFilteringRow = true;
        }

        private void SetupChildForUnbound(RadGridView radGridView1)
        {
            GridViewTemplate template = new GridViewTemplate();
            template.AllowAddNewRow = false;
            GridViewTextBoxColumn textBoxColumn = new GridViewTextBoxColumn("SessionID");
            textBoxColumn.HeaderText = "SessionID";
            template.Columns.Add(textBoxColumn);
            textBoxColumn = new GridViewTextBoxColumn("UserName");
            textBoxColumn.HeaderText = "UserName";
            template.Columns.Add(textBoxColumn);
            textBoxColumn = new GridViewTextBoxColumn("RemotePoint");
            textBoxColumn.HeaderText = "RemotePoint";
            template.Columns.Add(textBoxColumn);
            textBoxColumn = new GridViewTextBoxColumn("ServerName");
            textBoxColumn.HeaderText = "ServerName";
            template.Columns.Add(textBoxColumn);
            radGridView1.Templates.Add(template);
            template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
        }

        private void LoadDataForUnbound(RadGridView radGridView1)
        {
            radGridView1.MasterTemplate.Rows.Clear();
            radGridView1.Templates[0].Rows.Clear();
            foreach(VxiChatSession _session in _server.SessionCollections)
            {
                radGridView1.MasterTemplate.Rows.Add(_session.SessionID, _session.SessionBeginTime, _session.SeesionMember);
                foreach (VxiUserBase _user in _session.UserCollections)
                {
                    radGridView1.Templates[0].Rows.Add(_session.SessionID, _user.UserName, _user.RemotePoint.ToString(), _user.ServerName);
                }
            }
            foreach (GridViewRowInfo info in radGridView1.ChildRows)
            {
                info.IsExpanded = false;
            }
        }

        private void SetupFiltering(GridViewTemplate template, bool enableFiltering)
        {
            template.EnableFiltering = enableFiltering; 
            for (int i = 0; i < template.Templates.Count; i++) 
            { 
                SetupFiltering(template.Templates[i], enableFiltering); 
            } 
        }

        #endregion






    }
}
